package app.fitness.simplefragment;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import model.Timeline;

import org.achartengine.ChartFactory;
import org.achartengine.GraphicalView;
import org.achartengine.chart.BarChart.Type;
import org.achartengine.model.XYMultipleSeriesDataset;
import org.achartengine.renderer.XYMultipleSeriesRenderer;

import utils.Utils;
import android.content.Context;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
import app.fitness.fragment.DashBoardFragment;
import chart.AbstractDemoChart;

import com.razerzone.android.fitness.R;

import define.DashBoard;
import define.FitnessData;
import define.Key;
import define.TimeLine;

public class DashBoardCaloriesSimpleFragment extends Fragment {

	/**
	 * String section
	 */
	/**
	 * View section
	 */
	private static GraphicalView mChartView;
	private static LinearLayout mLl;
	public static LinearLayout mLlTimeDayMonthMonths;
	public static LinearLayout mLlTimeWeekly;
	public static LinearLayout mLlTimeYearly;
	private static TextView mTvActivity;
	public static TextView mTvCurrent;
	public static TextView mTvFirstDay;
	public static TextView mTvGoal;
	public static TextView mTvLastDay;
	public static TextView mTvMiddleDay;

	/**
	 * The others section
	 */

	/**
	 * Listener
	 */
	// private OnClickListener mListernerBack = new OnClickListener() {
	//
	// @Override
	// public void onClick(View v) {
	// Fragment mFm = new DashBoardFragment();
	// getFragmentManager().beginTransaction()
	// .replace(R.id.fr_content_activity_fitness, mFm)
	// .commitAllowingStateLoss();
	// getActivity().runOnUiThread(new Runnable() {
	//
	// @Override
	// public void run() {
	// ActivityFitness.mFm.executePendingTransactions();
	// }
	// });
	// }
	// };

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		/**
		 * Set Orientation for page
		 */
		getActivity().setRequestedOrientation(
				ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);

		View v = null;
		if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
			v = inflater.inflate(R.layout.simple_fragment_dashboard_calories,
					container, false);

			initialVariables(v);
			// initialData();
		}
		return v;
	}

	@Override
	public void onViewStateRestored(Bundle savedInstanceState) {
		super.onViewStateRestored(savedInstanceState);

		showData(getActivity(),
				DashBoardFragment.singleTon.getCaloriesCurrent(),
				DashBoardFragment.singleTon.getCaloriesGoal());
	}

	/**
	 * Initialize methods
	 */

	private void initialVariables(View v) {
		mLl = (LinearLayout) v
				.findViewById(R.id.ll_graph_in_simple_fragment_dashboard_calories);
		mLlTimeDayMonthMonths = (LinearLayout) v
				.findViewById(R.id.ll_time_day_month_months_in_simple_fragment_dashboard_calories);
		mLlTimeWeekly = (LinearLayout) v
				.findViewById(R.id.ll_time_weekly_in_simple_fragment_dashboard_calories);
		mLlTimeYearly = (LinearLayout) v
				.findViewById(R.id.ll_time_year_in_simple_fragment_dashboard_calories);
		mTvActivity = (TextView) v
				.findViewById(R.id.tv_activity_in_simple_fragment_dashboard_calories);
		mTvCurrent = (TextView) v
				.findViewById(R.id.tv_current_in_simple_fragment_dashboard_calories);
		mTvFirstDay = (TextView) v
				.findViewById(R.id.tv_first_day_in_simple_fragment_dashboard_calories);
		mTvGoal = (TextView) v
				.findViewById(R.id.tv_goal_in_simple_fragment_dashboard_calories);
		mTvLastDay = (TextView) v
				.findViewById(R.id.tv_last_day_in_simple_fragment_dashboard_calories);
		mTvMiddleDay = (TextView) v
				.findViewById(R.id.tv_middle_day_in_simple_fragment_dashboard_calories);
	}

	/**
	 * Basic methods
	 * 
	 * @throws IOException
	 */

	private static void drawChartView(Context context) {
		if (mChartView == null) {
			/**
			 * Initial Chart View
			 */
			mChartView = ChartFactory.getBarChartView(context,
					setUpDatasetChartView(), getBarChartRenderer(context),
					Type.STACKED);

			/**
			 * Add Chart View
			 */
			mLl.addView(mChartView, new LayoutParams(
					android.view.ViewGroup.LayoutParams.MATCH_PARENT,
					android.view.ViewGroup.LayoutParams.MATCH_PARENT));
		} else {
			/**
			 * Remove Chart View before update Chart View again
			 */
			Utils.removeViewParent(mChartView);

			/**
			 * Reset Chart View
			 */
			mChartView = null;

			/**
			 * Initial Chart View
			 */
			mChartView = ChartFactory.getBarChartView(context,
					setUpDatasetChartView(), getBarChartRenderer(context),
					Type.STACKED);

			/**
			 * Add Chart View
			 */
			mLl.addView(mChartView, new LayoutParams(
					android.view.ViewGroup.LayoutParams.MATCH_PARENT,
					android.view.ViewGroup.LayoutParams.MATCH_PARENT));
		}
	}

	private static List<double[]> getChartValue() {
		/**
		 * Total Records one day is 288 pattern
		 */
		List<double[]> mListValues = new ArrayList<double[]>();
		double[] value = null;
		/**
		 * get value chart
		 */

		DashBoard.CHOOSE_DATE_IN_ACTION_SHEET_DASH_BOARD = DashBoardFragment.singleTon
				.getCurrentTimePicker();

		switch (DashBoard.CHOOSE_DATE_IN_ACTION_SHEET_DASH_BOARD) {
		case Key.KEY_1_MONTH:
			// Day has column is 30
			value = new double[TimeLine.timelineMonthLocal.length];
			for (int i = 0; i < FitnessData.MONTH_CALORIES.length; i++) {
				value[i] = Double.valueOf(FitnessData.MONTH_CALORIES[i] + "");
			}
			break;
		case Key.KEY_3_MONTHS:
			// Day has column is 93
			value = new double[TimeLine.timelineMonthsLocal.length];
			for (int i = 0; i < FitnessData.MONTHS_CALORIES.length; i++) {
				value[i] = Double.valueOf(FitnessData.MONTHS_CALORIES[i] + "");
			}
			break;
		case Key.KEY_DAILY:
			// Day has column is 288
			// Day has column is 288
			value = new double[288];
			int index = 0;
			int j = 0;
			for (Long item : TimeLine.mLlFhdTimeLineDailyLocal) {
				Calendar calendar = Calendar.getInstance(); // creates a new
															// calendar instance
				calendar.setTimeInMillis(item.longValue() * 1000); // assigns
																	// calendar
																	// to given
																	// date

				Timeline timeline = new Timeline(
						calendar.get(Calendar.HOUR_OF_DAY),
						calendar.get(Calendar.MINUTE));
				index = ((timeline.getHour() * 60) + timeline.getMinute()) / 5;

				TimeLine.timelineDailyLocal[index] = timeline;

				if (j++ < FitnessData.DAILY_CALORIES.length) {
					value[index] = Double
							.valueOf(FitnessData.DAILY_CALORIES[j++]);
				}
			}
			break;
		case Key.KEY_WEEKLY:
			// Day has column is 7
			value = new double[TimeLine.timelineWeekLocal.length];
			for (int i = 0; i < FitnessData.WEEK_CALORIES.length; i++) {
				value[i] = Double.valueOf(FitnessData.WEEK_CALORIES[i] + "");
			}
			break;
		case Key.KEY_YEARLY:
			// Day has column is 12
			value = new double[TimeLine.timelineYearLocal.length];
			for (int i = 0; i < FitnessData.YEAR_CALORIES.length; i++) {
				value[i] = Double.valueOf(FitnessData.YEAR_CALORIES[i] + "");
			}
			break;
		default:
			break;
		}

		mListValues.add(value);

		return mListValues;
	}

	private static XYMultipleSeriesDataset setUpDatasetChartView() {
		String[] titles = new String[] { "" };

		/**
		 * Get Values to draw on Chart
		 */
		if (!getChartValue().isEmpty()) {
			XYMultipleSeriesDataset mDataset = AbstractDemoChart
					.buildBarDataset(titles, getChartValue());

			return mDataset;
		}

		return null;
	}

	private static XYMultipleSeriesRenderer getBarChartRenderer(Context context) {
		int[] colors = new int[] { context.getResources().getColor(
				R.color.green_text) };
		XYMultipleSeriesRenderer renderer = AbstractDemoChart
				.buildBarRenderer(colors);

		renderer.setAntialiasing(true);
		renderer.setAxesColor(Color.BLACK);
		renderer.setBarSpacing(4f);
		renderer.setGridColor(Color.BLACK);
		renderer.setMarginsColor(Color.argb(0x00, 0x01, 0x01, 0x01));
		renderer.setPanEnabled(false);
		renderer.setShowGridX(true);
		renderer.setShowAxes(false);
		renderer.setShowLegend(false);
		renderer.setXLabels(0);
		renderer.setYLabels(0);
		renderer.setYLabelsColor(0, Color.TRANSPARENT);
		renderer.setZoomEnabled(false, false);

		// TODO
		switch (DashBoardFragment.singleTon.getCurrentTimePicker()) {
		case Key.KEY_1_MONTH:
			renderer.setXAxisMax(TimeLine.timelineMonthLocal.length);
			break;
		case Key.KEY_3_MONTHS:
			renderer.setXAxisMax(TimeLine.timelineMonthsLocal.length);
			break;
		case Key.KEY_DAILY:
			renderer.setXAxisMax(TimeLine.timelineDailyLocal.length);
			break;
		case Key.KEY_WEEKLY:
			renderer.setXAxisMax(TimeLine.timelineWeekLocal.length);
			break;
		case Key.KEY_YEARLY:
			renderer.setXAxisMax(TimeLine.timelineYearLocal.length);
			break;
		default:
			break;
		}

		return renderer;
	}

	public static void showData(Context context, String current, String goal) {
		mTvActivity.setText(context.getString(R.string.calories_));

		/**
		 * Set activities data
		 */
		mTvCurrent.setText(Utils.showIntergerFormat(current));
		mTvGoal.setText(Utils.showIntergerFormat(goal.replace(",", "")));

		/**
		 * Check current time picker to decide show which time line below chart
		 */
		DashBoardFragment.showTimeLine(context);

		// Draw chart
		if (Float.valueOf(current) > 0) {
			drawChartView(context);
		}
	}
}
